package com.xzx.shop_front_api.controller;

import com.xzx.shop_front_api.service.AlipayService;
import com.xzx.shop_front_api.service.GoodsService;
import com.xzx.shop_front_api.service.OrderService;
import com.xzx.shop_front_api.utils.JsonResult;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpResponse;

@Controller
@RequestMapping("api/alipay")
public class AliPayController {
    @Autowired
    private AlipayService alipayService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;

    @GetMapping("create")
    public void create(@RequestParam("order_no") String orderNo,
                             @RequestParam("subject") String subject,
                             @RequestParam("pay_amount") String payAmount,
                             HttpServletResponse response

                             ) throws Exception {
        // 创建支付表单
        String form = alipayService.createPay(subject, payAmount,orderNo);
        // 将表单输出到页面
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }
    //同步回调
    @GetMapping("return")
    public void returnPay(HttpServletResponse response) throws Exception {
        // 将表单输出到页面
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("支付成功");
        response.getWriter().flush();
        response.getWriter().close();
    }
    //异步回调通知
    @PostMapping("callback")
    public String callback(HttpServletRequest request,HttpServletResponse response) throws Exception {
        //修改订单状态，改成待发货 支付状态改为已支付
        String tradeStatus = request.getParameter("trade_status");
        String out_trade_no = request.getParameter("out_trade_no");
        String gmtPayment = request.getParameter("gmt_payment");
        String tradeNo = request.getParameter("trade_no");
        if (!"TRADE_SUCCESS".equals(tradeStatus)) {
            return "FAIL";
        }
        //修改订单订单状态，支付状态，扣减实际库存
        //orderService.updateOrderStatusPayStatus(out_trade_no,1,1,gmtPayment,1,tradeNo);
        //扣减实际库存
        //goodsService.updateStock(out_trade_no);
        //消息通知

        return "TRADE_SUCCESS";

    }

}
